package com.jservice.api.smkAppUser;

import com.jfinal.kit.HashKit;
import com.jservice.api.dto.Request;
import com.jservice.framework.cache.JCacheKit;
import com.jservice.framework.utils.DateUtils;
import com.jservice.framework.utils.StringUtils;
import com.jservice.model.SmkAppUser;

import java.util.Date;
import java.util.UUID;

/**
 * App 登录用户缓存KIT
 *
 * @author cwvian
 * @version 1.0
 * @date 2017/6/7
 */
public class AppUserKit {

    private final static String CACHE_NAME = "APP_SESSION";

    public static String getToken(String idCard) {
        int random = (int) (10 + (Math.random() * 10));
        String salt = UUID.randomUUID().toString().replace("-", "").substring(random);// 随机长度
        return HashKit.sha256(idCard + salt);
    }

    public static String addAppUser(SmkAppUser appUser) {
        String token = getToken(appUser.getIdCard());
        JCacheKit.put(CACHE_NAME, token, appUser);
        return token;
    }

    public static SmkAppUser getCurrent(String token) {
        SmkAppUser appUser = SmkAppUser.dao.doFindFirst("token = ? ", token);
        if (appUser != null) {
            if (appUser.getLoginDate() != null && DateUtils.getDistanceOfTwoDate(appUser.getLoginDate(), new Date()) < 30) {
                return appUser;
            }
        }
        return null;
    }

    public static SmkAppUser getCurrent(Request request) {
        String token = request.getHeader().getToken();
        if (StringUtils.isBlank(token)) {
            return null;
        }
        return getCurrent(token);
    }

}
